package com.adresvseti.wallpaperoid.services;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;

import com.adresvseti.wallpaperoid.constants.Settings;
import com.adresvseti.wallpaperoid.helpers.WallpaperXmlParser;
import com.adresvseti.wallpaperoid.models.Wallpaper;

public class WallpapersService {

	
	/** Retrieves list of Wallpapers for specified category asynchronously.
	 * @param categoryId	Category id.
	 * @param callback		Callback method.
	 * @return
	 */
	public void getWallpapersAsync(int categoryId, final IGetWallpapersCallback callback) {
		
		DownloadXmlTask downloadTask =  new DownloadXmlTask(new IDownloadXmlSuccessCallback() {
			
			@Override
			public void success(String result) {
				
				// parsing wallpapers xml
				InputStream is = new ByteArrayInputStream(result.getBytes(Charset.defaultCharset()));
				
				WallpaperXmlParser parser = new WallpaperXmlParser();
				
				try {
					List<Wallpaper> wallpapers = parser.parse(is);
					callback.success(wallpapers);
				} catch (Exception e) {
					callback.success(null);
				}
			}
		});
		
		downloadTask.execute(Settings.API_URL_WALLPAPERS + categoryId);
	}
	
	
	/** Builds wallpaper thumb url.
	 * @param wallpaperId
	 * @param width
	 * @param height
	 * @param method: 0 = crop, 1 = max, 2 = min, 3 = pad
	 * @param quality
	 * @return
	 */
	public String getWallpaperUrl(int wallpaperId, int width, int height, int method, int quality)
	{
		return Settings.URL_WALLPAPER_THUMB + "?id=" + wallpaperId + "&width=" + width + "&height=" + height + "&method=" + method + "&quality=" + quality;
	}
	
}
